import axios, {
  type AxiosError,
  type AxiosInstance,
  type AxiosRequestConfig,
  type AxiosResponse,
  type InternalAxiosRequestConfig,
  type Method,
} from "axios";
import { localhost } from "./storage";

export const http: AxiosInstance = axios.create({
  baseURL: "/dev-api",
  timeout: 10000,
});

// 添加请求拦截器
http.interceptors.request.use(
  function (config: InternalAxiosRequestConfig) {
    const token = localhost.get("token");
    config.headers.Authorization = `Bearer ${token}`;
    // 在发送请求之前做些什么
    return config;
  },
  function (error: AxiosError) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
http.interceptors.response.use(
  function (response: AxiosResponse) {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    return response;
  },
  function (error: AxiosError) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);

type DataType<T = any> = {
  data: T;
  code: number;
  message: string;
};

const request = <T = any>(
  url: string,
  method: Method = "GET",
  data?: Object,
  options?: AxiosRequestConfig
) => {
  return http.request<T, DataType<T>>({
    url,
    method,
    [method === "GET" ? "params" : "data"]: data,
    ...options,
  });
};

export const get = <T = any>(url: string, data?: Object) => {
  request<T>(url, "GET", data);
};

export const post = <T = any>(url: string, data?: Object) => {
  request<T>(url, "POST", data);
};

export const put = <T = any>(url: string, data?: Object) => {
  request<T>(url, "PUT", data);
};

export const del = <T = any>(url: string, data?: Object) => {
  request<T>(url, "DELETE", data);
};

export default request;
